package com.zbw.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class Callback implements MqttCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(Callback.class);

    @Override
    public void connectionLost(Throwable cause) {
        LOGGER.debug("connection lost,cause:{}", cause);
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        LOGGER.info("Received Topic:{}", topic);
        LOGGER.info("Received Message QOS:{}", message.getQos());
        LOGGER.info("Received Message ID:{}", message.getId());
        LOGGER.info("Received Message Body:{}", new String(message.getPayload(), StandardCharsets.UTF_8));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        try {
            LOGGER.debug("delivery complete,message:{},complete:{}", token.getMessage(), token.isComplete());
        } catch (MqttException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
